package com.star.common.utils;


import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.star.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.util.Arrays;

/**
 * 加密工具类
 *
 * @author yangzj
 */
@Slf4j
public class Encrypts {

    private final static String PRIVATE = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAPYPQIMcvtQDl0ey8S/u9Eun5Dvc9ux0gyX1m+Rm7FIW21qwHbKb7tZs1jbncyG0ZE+DEliYbLUcxDeSZZL/ciT+cN2UwfkjlH5kEdUJoivkerOLWCN32Szr+UfPoB5neF8YhL3GD8dqI4rAM33DNLLaKqZtJVE93wlsc1sjJvyJAgMBAAECgYALVQH9V9RRCtZLgsn5UWm2V0XbXO6RTr9gfup+TyAomq1hBJXljSlnfi0ya5/hiD+LauesJV7yS2AdCBS9+547z07SY8Qj6V4KIud/MkwLMZn0UpRjjBggu+BRHH3NTEWQZJI01sjtVk2KnyFs7Uy9IcaVbdRps12b9V2pDz+bQQJBAPxnUoFSCCgxBAC5uo0eU3k0tVrHsRXpIOB4wS2Ct2eZzK8/D5nkcpU7asZyaGfoiXMeo3gjIiKysOJUktsX+GkCQQD5kMn7U0zm86VlLXlkrqLzWa1QPy5W2qqcUsoJc3I7RkS1AXPRpYWKK/bIPPRNGQXMmPB+1DXeLzkuMHkcuV8hAkEAmWzA5SUVGkE5OqurLy649NtKReVOyo/MUUZ1vpFPpOUDW59Mf3IzCG12qSxQNKFQM67zFQreLBNMnDdmkVFPyQJBAMon5eVGudGO5ZhKuL281NRo/QI227ORV4hfa7cyJAMtzXQN5CKbgMvHBxV2grJ9JXxxGsax4ZzEBf6LV1/ULOECQQDQcdVzkjC0DmNR/2pFo83JwIOylyG6mD8DHI8MsbZx6ZPwHZDZuuXtrSmi1600gIGXJuKJvkZrosJh6nvD8EEe";
    private final static String PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD2D0CDHL7UA5dHsvEv7vRLp+Q73PbsdIMl9ZvkZuxSFttasB2ym+7WbNY253MhtGRPgxJYmGy1HMQ3kmWS/3Ik/nDdlMH5I5R+ZBHVCaIr5Hqzi1gjd9ks6/lHz6AeZ3hfGIS9xg/HaiOKwDN9wzSy2iqmbSVRPd8JbHNbIyb8iQIDAQAB";
    private final static RSA RSA = new RSA(PRIVATE, PUBLIC);

    /**
     * 加密
     *
     * @param str str
     * @return {@link String}
     */
    public static String encrypt(String str) {
        return RSA.encryptBase64(str, KeyType.PublicKey);
    }

    /**
     * 加密数组长度
     */
    public static final int ENCRYPT_LENGTH = 3;

    /**
     * 自定义解密
     * 解密
     *
     * @param encryptStr 加密字符
     * @return {@link Long[]}
     */
    public static Long[] customDecrypt(String encryptStr) {
        String decrypt = Encrypts.decrypt(encryptStr);
        if (StrUtil.isBlank(decrypt) || !decrypt.contains(StrPool.COMMA)) {
            throw new BizException("不存在");
        }
        String[] split = decrypt.split(StrPool.COMMA);
        if (split.length != ENCRYPT_LENGTH) {
            throw new BizException("不存在");
        }
        long id;
        long owner;
        try {
            id = Long.parseLong(split[0]);
            owner = Long.parseLong(split[1]);
        } catch (NumberFormatException e) {
            throw new BizException("不存在");
        }
        return new Long[]{id, owner};
    }
    /**
     * 解密
     *
     * @param str str
     * @return {@link String}
     */
    public static String decrypt(String str) {
        try {
            return RSA.decryptStr(str, KeyType.PrivateKey);
        } catch (Exception e) {
            log.error("解密失败，str={}", str, e);
            throw new BizException("解析错误");
        }
    }

    public static void main(String[] args) {
        Long id = 1323238929322332L;
        Long userId = 1323238929322332L;
        String str = id + StrPool.COMMA + userId + StrPool.COMMA + System.currentTimeMillis();
        String encrypt = Encrypts.encrypt(str);
        Long[] longs = Encrypts.customDecrypt(encrypt);
        for (int i = 0; i < longs.length; i++) {
            System.out.println(longs[i]);
        }
        /*<pre>
        RSA rsa = new RSA();
        //获得私钥
        String privateKeyBase64 = rsa.getPrivateKeyBase64();
        //获得公钥
        String publicKeyBase64 = rsa.getPublicKeyBase64();
        System.out.println(privateKeyBase64);
        System.out.println("---------");
        System.out.println(publicKeyBase64);
        */
        /*String str = "1,2,3";
        // 加密
        String encrypt = "GWg4jjbnYi5UZfmVsIta1X6xfSUrtvoezjlp3sWzupePA2JsZ6j414+jwnXacuWJPLW6kRqiPxSCDAb4IpV2J7M7IP+L0WaQ7Oc78uQEzFlACXYiGH9J2cFdc3QJPYL7IyuQcJhkTh+5zfWc124oMKbq+ppx9qYVWpP+C5/8my8=";
        System.out.println("加密内容：" + encrypt);
        // 解密
        String s = RSA.decryptStr(encrypt, KeyType.PrivateKey);
        System.out.println("解密内容：" + s);*/
    }


    /**
     * 用SHA1算法生成安全签名
     *
     * @param values 值
     * @return {@link String}
     * @throws Exception 例外
     */
    public static String getSHA1(String... values) throws Exception {

        try {
            String[] array = new String[values.length];
            for (int i = 0; i < values.length; i++) {
                array[i] = values[i];
            }

            StringBuffer sb = new StringBuffer();
            // 字符串排序
            Arrays.sort(array);
            for (int i = 0; i < values.length; i++) {
                sb.append(array[i]);
            }
            String str = sb.toString();
            // SHA1签名生成
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(str.getBytes());
            byte[] digest = md.digest();

            StringBuffer hexstr = new StringBuffer();
            String shaHex = "";
            for (int i = 0; i < digest.length; i++) {
                shaHex = Integer.toHexString(digest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexstr.append(0);
                }
                hexstr.append(shaHex);
            }
            return hexstr.toString();
        } catch (Exception e) {
            throw new BizException("SHA1加密失败");
        }

    }
}
